package com.example.lenovo.startproject329zay.model;

import retrofit2.Call;


import com.example.lenovo.startproject329zay.bean.WeatherResult;
import com.example.lenovo.startproject329zay.iface.WeatherListener;
import com.example.lenovo.startproject329zay.iface.Weatheriface;
import com.example.lenovo.startproject329zay.service.WeatherService;

import retrofit2.Callback;
import retrofit2.Response;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;


/**
 * Created by lenovo on 2017/3/23.
 */

public class WeatherModel implements Weatheriface{
    private Retrofit retrofit;
    private  String BASEURL="http://www.weather.com.cn/";

    public WeatherModel() {
        System.out.println("----WeatherModel构造函数");
        //Retrofit实例化，3-1
        retrofit=new Retrofit.Builder().baseUrl(BASEURL).addConverterFactory(GsonConverterFactory.create()).build();
    }

    @Override
    public void getWeather(String cityno, final WeatherListener listener) {
        System.out.println("----WeatherModel构造函数");
        //Retrofit接口使用3-2
        WeatherService weatherService=retrofit.create(WeatherService.class);
        Call<WeatherResult> call=weatherService.getResult(cityno);
        //Retrofit接口使用3-3
        call.enqueue(new Callback<WeatherResult>() {
            @Override
            public void onResponse(Call<WeatherResult> call, Response<WeatherResult> response) {
                if (response.isSuccessful()&&response.body()!=null)
                    listener.onResponse(response.body().getWeatherinfo());
                else
                    listener.onFail("onResponse error");
            }

            @Override
            public void onFailure(Call<WeatherResult> call, Throwable t) {
                listener.onFail(t.toString());
            }
        });

    }
}
